'''
Created on Sep 24, 2012

@author: peng
'''
import MySQLdb


BELUGA_DB_CONFIG = {'host': '10.42.133.171',
                    'user': 'dev_analysis',
                    'password': 'analysis_dev_pwd',
                    'db': 'beluga_analysis',
                    'port': 3306}


class MySQLdbWrapper:

    conn = None

    def connect(self):
        self.conn = MySQLdb.connect(host=BELUGA_DB_CONFIG['host'],
                                    user=BELUGA_DB_CONFIG['user'],
                                    passwd=BELUGA_DB_CONFIG['password'],
                                    db=BELUGA_DB_CONFIG['db'],
                                    port=BELUGA_DB_CONFIG['port'])
        self.conn.set_character_set('utf8')
        self.conn.autocommit(True)

    def cursor(self):
        try:
            # if not self.conn:
            self.connect()
            return self.conn.cursor()
        except MySQLdb.OperationalError:
            self.connect()
            return self.conn.cursor()

_db = MySQLdbWrapper()


def get_data(sql_list):
    try:
        cursor = _db.cursor()
        sql = ' '.join(sql_list)
        cursor.execute(sql)
        data = cursor.fetchall()
        return data
    finally:
        cursor.close()


if __name__ == '__main__':
    sql_list = []
    sql_list.append('SELECT app_key, udid FROM')
    sql_list.append('dim_app_udid_basic')
    sql_list.append('limit 100000 OFFSET %s')

    f = open('/mnt/export/new_user', 'w')

    offset = 0

    while True:
        sql = ' '.join(sql_list)
        rows = get_data([sql % offset])
        print sql
        if len(rows) == 0:
            break
        for row in rows:
            if len(row[0]) != 32 or len(row[1]) != 32:
                continue
            f.write(row[0] + '\t' + row[1])
            f.write('\n')
        offset += 100000
    f.close()
